import os
from google.appengine.ext.webapp import template

from google.appengine.ext import webapp

from models.Authentication import *
import logging
import uuid

class Registration(webapp.RequestHandler):
  """This is the controller that will handle all of the new user 
  registration"""
  def get(self, flash=None):
    """Render the Registration template"""
    template_values = {"flash":flash}
    path= os.path.join(os.path.dirname(__file__), "../templates/register.html")
    self.response.out.write(template.render(path, template_values))
    
  def post(self):
    """This will do the creation of a new user"""
    password = self.request.get("pword")
    con_password = self.request.get("con_pword")
    email = self.request.get("email")
    logging.info(str(password))
    logging.info(str(con_password))
    logging.info(email)
    
    if password != con_password:
      flash = "Your passwords did not match"
      self.get(flash=flash)
    else:
      query = User.all()
      query.filter("email = ", email)
      result = query.get()
      # logging.info(result.email)
      
      if not result:
        new_user = User(email=email)
        new_user.password = password
        new_user.displayname = email
        new_user.put()
        
        # add the session automatically
        cookie = Cookie.SimpleCookie()
        cookie["user_id"] = new_user.key().id()
        cookie["session_id"] = str(uuid.uuid4())
        self.response.headers.add_header('Set-Cookie', cookie.output("header="))
        
        return self.redirect("/group")
      
      else:
        flash = "That email address is already linked to an account"
        self.get(flash=flash)
        
      
  
